package com.tendory.jt808.msg;

import android.util.Log;

import com.tendory.jt808.util.IntegerUtils;
import com.tendory.jt808.util.LogUtils;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class CommandReply extends Message {

    private static final String TAG = LogUtils.makeTag(CommandReply.class);

    public static final short ID = (short) 0x8105;

    private final byte command;
    private final String parameter;
    private final short sn;

    private CommandReply(Builder builder) {
        super(ID, builder.cipher, builder.phone, builder.body);

        command = builder.command;
        parameter = builder.parameter;
        sn = builder.base.getSn();
    }

    public byte getCommand() {
        return command;
    }

    public String getParameter() {
        return parameter;
    }

    @Override
    public short getSn() {
        return sn;
    }

    @Override
    public String toString() {
        return "CommandReply{" +
                "command=" + command +
                ", parameter='" + parameter + '\'' +
                '}';
    }

    public static class Builder extends MessageBuilder {

        // Required parameters
        private byte command;
        private String parameter;
        private Message base;

        public Builder(Message msg) {
            if (msg == null) {
                throw new NullPointerException("Message is null.");
            }
            if (ID != msg.getId()) {
                throw new IllegalArgumentException("Wrong message ID.");
            }

            this.cipher = msg.getCipher();
            this.phone = msg.getPhone();
            this.body = msg.getBody();
            this.base = msg;
//      if (this.body.length != 5) {
//        throw new IllegalArgumentException("Message body incorrect.");
//      }

            this.command = IntegerUtils.parseByte(Arrays.copyOfRange(this.body, 0, 1)); //TODO
            try {
                this.parameter = new String(Arrays.copyOfRange(this.body, 1, this.body.length), "ascii");
            } catch (UnsupportedEncodingException uee) {
                Log.e(TAG, "Builder: Encode authentication code failed.", uee);
            }
        }

        @Override
        public CommandReply build() {
            return new CommandReply(this);
        }

    }

}
